package com.edroid.apkhooker.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

final class SettingsSystemData{
	public int _id;
	public String imei,key,value,dataType;
}

public final class SettingsSystemDB extends SQLiteOpenHelper{
	private static final String TAG = "SettingsSystemDB";
	
	private static enum SystemTab{
		_id,IMEI,KEY,VALUE,DATATYPE;
	}
	private static final String SQL_CREATE_TABLE = 
			"CREATE TABLE IF NOT EXISTS "+SystemTab.class.getSimpleName()+" ("
			+ SystemTab._id.name() + " INTEGER PRIMARY KEY,"
			+ SystemTab.IMEI.name() + " TEXT UNIQUE ON CONFLICT REPLACE," //如果违反唯一约束，用新值替代
			+ SystemTab.KEY.name() + " TEXT,"
			+ SystemTab.VALUE.name() + " TEXT,"
			+ SystemTab.DATATYPE.name() + " TEXT)";
	
	public SettingsSystemDB(Context context, String name) {
		super(context, name, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.e(TAG, String.format("onUpgrade oldVersion=%d,newVersion=%d", oldVersion, newVersion));
	}
	
	/**
	 * @return 成功返回新行的行ID，失败返回-1
	 */
	public long insert(String imei,String key,String value,String dataType){
		ContentValues values = new ContentValues();
		values.put(SystemTab.IMEI.name(), imei);
		values.put(SystemTab.KEY.name(), key);
		values.put(SystemTab.VALUE.name(), value);
		values.put(SystemTab.DATATYPE.name(), dataType);
		return getWritableDatabase().insert(SystemTab.class.getSimpleName(), null, values);
	}
	
	public SettingsSystemData query(String imei){
		Cursor cursor = getReadableDatabase().query(SystemTab.class.getSimpleName(), null, 
				SystemTab.IMEI.name()+"=?", new String[]{imei}, null, null, null);
		try{
			if(cursor.moveToFirst()){
				SettingsSystemData data = new SettingsSystemData();
				data._id = cursor.getInt(SystemTab._id.ordinal());
				data.imei = cursor.getString(SystemTab.IMEI.ordinal());
				data.key = cursor.getString(SystemTab.KEY.ordinal());
				data.value = cursor.getString(SystemTab.VALUE.ordinal());
				data.dataType = cursor.getString(SystemTab.DATATYPE.ordinal());
				return data;
			}
		}finally{
			cursor.close();
		}
		return null;
	}
	
	public void deleteAll(){
		getWritableDatabase().delete(SystemTab.class.getSimpleName(), null, null);
	}
}
